package com.npjscg.medicalpro.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.npjscg.medicalpro.common.Constants;
import com.npjscg.medicalpro.common.Result;
import com.npjscg.medicalpro.config.AuthAccess;
import com.npjscg.medicalpro.controller.dto.UserDTO;
import com.npjscg.medicalpro.controller.dto.UserPasswordDTO;
import com.npjscg.medicalpro.entity.User;
import com.npjscg.medicalpro.entity.Validation;
import com.npjscg.medicalpro.exception.ServiceException;
import com.npjscg.medicalpro.service.IUserService;
import com.npjscg.medicalpro.service.IValidationService;
import com.npjscg.medicalpro.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author raote
 * @since 2022-06-23
 */
@Api(tags = "用户管理模块")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;


    @Autowired
    private IValidationService validationService;

    //返回所有数据库用户，仅用于测试
    @ApiOperation(value = "返回所有数据库用户，仅用于测试")
    @GetMapping("/all")
    public List<User> findall() {
        return userService.list();
    }


    // 发送邮箱验证码
    @AuthAccess
    @ApiOperation(value = "发送验证码")
    @GetMapping("/email/{email}/{type}")
    public Result sendEmailCode(@PathVariable String email, @PathVariable Integer type) throws MessagingException {
        if(StrUtil.isBlank(email)) {
            throw new ServiceException(Constants.CODE_400, "参数错误");
        }
        if(type == null) {
            throw new ServiceException(Constants.CODE_400, "参数错误");
        }
        userService.sendEmailCode(email, type);
        return Result.success();
    }

    // 邮箱登录
    @AuthAccess
    @ApiOperation(value = "邮箱登录")
    @PostMapping("/loginEmail")
    public Result loginEmail(@RequestBody UserDTO userDTO) {
        String email = userDTO.getEmail();
        String code = userDTO.getCode();
        if (StrUtil.isBlank(email) || StrUtil.isBlank(code)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        UserDTO dto = userService.loginEmail(userDTO);
        return Result.success(dto);
    }


    //登录
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = SecureUtil.md5(userDTO.getPassword());
        userDTO.setPassword(SecureUtil.md5(userDTO.getPassword()));
        int role =userDTO.getRole();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password) ){
            return Result.error(Constants.CODE_400, "参数错误");
        }
        UserDTO dto = userService.login(userDTO);
        return Result.success(dto);



    }
    //token校验
    @ApiOperation(value = "前端路由的token验证")
    @GetMapping ("/checktoken")
    public Boolean checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        String password = request.getHeader("password");
        System.out.println(TokenUtils.verify(token, password));
        return TokenUtils.verify(token, password);
    }

    // 忘记密码 | 重置密码
    @AuthAccess
    @PutMapping("/reset")
    public Result reset(@RequestBody UserPasswordDTO userPasswordDTO) {
        if (StrUtil.isBlank(userPasswordDTO.getEmail()) || StrUtil.isBlank(userPasswordDTO.getCode())) {
            throw new ServiceException("-1", "邮箱验证码不能为空！");
        }
        // 先查询 邮箱验证的表，看看之前有没有发送过  邮箱code，如果不存在，就重新获取
        QueryWrapper<Validation> validationQueryWrapper = new QueryWrapper<>();
        validationQueryWrapper.eq("email", userPasswordDTO.getEmail());
        validationQueryWrapper.eq("code", userPasswordDTO.getCode());
        validationQueryWrapper.ge("time", new Date());  // 查询数据库没过期的code, where time >= new Date()
        Validation one = validationService.getOne(validationQueryWrapper);
        if (one == null) {
            throw new ServiceException("-1", "验证码过期，请重新获取");
        }

        // 如果验证通过了，就查询要不过户的信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", userPasswordDTO.getEmail());  //存根据email查询用户信息
        User user = userService.getOne(userQueryWrapper);

        // 重置密码
        user.setPassword(SecureUtil.md5("123456"));
        userService.updateById(user);
        return Result.success();
    }

    //修改密码
    @ApiOperation(value = "修改密码")
    @PostMapping("/password")
    public Result changePassword(@RequestBody UserPasswordDTO userPasswordDTO ,HttpServletRequest servletRequest) {
        userPasswordDTO.setPassword(SecureUtil.md5(userPasswordDTO.getPassword()));
        userPasswordDTO.setNewPassword(SecureUtil.md5(userPasswordDTO.getNewPassword()));
        userService.changePassword(userPasswordDTO);
        return Result.success();

    }

    //注册
    @ApiOperation(value = "用户新增")
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        return Result.success(userService.register(userDTO));
    }


    //分页查询
    //  查询所有非管理员用户：localhost:8082/
    //需要传入当前页号、当前页面需要多少条记录
    @ApiOperation(value = "分页查询")
    @GetMapping(value = {"/findAll/{pagenum}/{pagesize}/{username}", "/findAll/{pagenum}/{pagesize}"})
    public Result findAll(@PathVariable int pagenum, @PathVariable int pagesize, @PathVariable(required = false) String username){
        //设置起始值及每页条数
        if (username == null)
            username = "";
        Page<User> page = new Page<>(pagenum,pagesize);
        return Result.success(userService.selectPage(page, username));
    }






    @ApiOperation(value = "删除用户")
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable int id){

        try {
            if(userService.removeById(id))
                return Result.success();
            else
                return Result.error(Constants.CODE_400,"系统中无该用户");
        } catch (ServiceException e) {
            throw e;
        }
    }

    //编辑用户,仅编辑用户名，密码，昵称，机构  注意如果传入null则数据库中内容会被修改为null，前端务必校验用户输入
    @ApiOperation(value = "编辑用户")
    @PostMapping("/edit")
    public Result editUser(@RequestBody UserDTO userDTO) {

        userService.edit(userDTO);
        return Result.success();
    }

    @PostMapping("/avatar")
    public Result avatar(@RequestBody User user){
        String avatar = user.getAvatar();
        if (avatar == null)
            return Result.error();
        return Result.success(userService.saveOrUpdate(user));
    }


    @GetMapping("/id/{id}")
    public Result getById(@PathVariable int id){
        User byId = userService.getById(id);
        if (byId == null)
            return Result.error();
        return Result.success(byId);
    }



}
